import { searchBykeyword, fileUtils, downloadImgs, exitTLS, pushToWeChat, fakeExitTLS } from './axios.js'

main()

// ===================== 主函数 =====================
export async function main(reLunchTimes = 10) {
  let { keywordsToProcess, PageToprocess } = fileUtils.resumeCrawling()

  try {
    for (const keyword of keywordsToProcess) {
      console.log(`\n✨ 正在爬取关键词 ${keyword} ...`)
      let reachedEnd = false
      // 从上次爬取的页码开始
      let page = PageToprocess
      PageToprocess = 1

      while (!reachedEnd) {
        const res = await searchBykeyword(keyword, page)

        if (!res) continue
        if (res.pages <= page || res.imgs.length === 0) reachedEnd = true

        console.log(`✨ 正在下载第 ${page} 页的图片（总共 ${res.pages} 页， ${res.total} 张图片）`)
        await downloadImgs(keyword, res.imgs)

        fileUtils.writeConfig({ lastProcessedPage: page++ }) // 存档已爬取页码
      }

      console.log(`✅ ${keyword}的图片下载完成！\n`)
      fileUtils.writeConfig({ lastProcessedKeyword: keyword }) // 存档爬取关键词
    }
  } catch (error) {
    fileUtils.logError(error)

    // 如果脚本被阻塞，自动重启
    if (reLunchTimes === 0) {
      console.log('❌ 达到最大重启次数！爬虫进程结束...')
      pushToWeChat('pixabay.com\n达到最大自动重启次数！爬虫挂了/(ㄒoㄒ)/~~\n目前爬取了 ' + fileUtils.config.lastEcPage + ' 页！\n@周辉 @邓雄威 来人！救虫啊！')
      exitTLS()
    } else {
      fakeExitTLS()
      fileUtils.logError('❌ 脚本阻塞，正在自动重启...')
      main(reLunchTimes - 1)
    }
  }
}
